package myky.com.doctorapp.ui;

import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Message;
import android.os.Process;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.github.nukc.stateview.Constant;
import com.gyf.barlibrary.ImmersionBar;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;


import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import myky.com.doctorapp.R;
import myky.com.doctorapp.entity.DownLoadFileEntity;
import myky.com.doctorapp.entity.VersionEntity;
import myky.com.doctorapp.base.BaseActivity;
import myky.com.doctorapp.contract.MainActivityContract;
import myky.com.doctorapp.fragment.HomeFragment;
import myky.com.doctorapp.fragment.MineFragment;
import myky.com.doctorapp.fragment.RemoteFragment;
import myky.com.doctorapp.presenter.MainActivityPresenter;
import myky.com.doctorapp.utils.DownLoaderManger;
import myky.com.doctorapp.utils.SystemUtil;
import myky.com.doctorapp.utils.ThreadUtil;
import myky.com.doctorapp.utils.ToastUtils;
import myky.com.doctorapp.utils.dbhelper.OnProgressListener;
import myky.com.doctorapp.utils.dbhelper.UpdateProgressDialog;
import myky.com.doctorapp.wight.SelfDialog;


/**
 * @author Mr.li
 */
public class MainActivity extends BaseActivity<MainActivityPresenter, VersionEntity.PayLoadBean> implements MainActivityContract.View, OnProgressListener {

    @BindView(R.id.fragment_container)
    FrameLayout fragmentContainer;
    @BindView(R.id.div_tab_bar)
    View divTabBar;
    @BindView(R.id.txt_home)
    TextView txtHome;
    @BindView(R.id.txt_remote)
    TextView txtRemote;
    @BindView(R.id.txt_mine)
    TextView txtMine;
    @BindView(R.id.tab_menu)
    LinearLayout tabMenu;

    private final int HOME_INDEX = 0;
    private final int REMOTE_INDEX = 1;
    private final int CENTER_INDEX = 2;

    private Context mContext;

    private int isForcedUpdate;

    private DownLoadFileEntity mFileInfo;

    private DownLoaderManger mDownLoaderManger = null;

    private UpdateProgressDialog mUpdateProgressDialog;

    private Fragment f1, f2, f3;

    private static SelfDialog selfDialog;

    final boolean[] isDown = {false};

    private boolean isStart = false;

    private int currentIndex = -1;

    @Override
    protected void reloadActivity() {
        //mPresenter.checkVersion();
    }

    @Override
    protected View injectTarget() {
        return findViewById(R.id.div_tab_bar);
    }

    @Override
    protected void initData() {
        changeNavagationState(HOME_INDEX);
        // mPresenter.checkVersion();
    }

    @Override
    public MainActivityPresenter getPresenter() {
        return new MainActivityPresenter();
    }

    @Override
    protected void initView() {
        ImmersionBar.with(this).init();
        mContext = MainActivity.this;
    }

    @Override
    public int getContenView() {
        return R.layout.activity_main;
    }

    //重置所有文本的选中状态
    public void selected() {
        txtHome.setSelected(false);
        txtRemote.setSelected(false);
        txtMine.setSelected(false);
    }

    //隐藏所有Fragment
    public void hideAllFragment(FragmentTransaction transaction) {
        if (f1 != null) {
            transaction.hide(f1);
        }
        if (f2 != null) {
            transaction.hide(f2);
        }
        if (f3 != null) {
            transaction.hide(f3);
        }

    }


    @OnClick({R.id.txt_home, R.id.txt_remote, R.id.txt_mine})
    public void onViewClick(View v) {
        switch (v.getId()) {
            case R.id.txt_home:
                if (currentIndex == 0) {
                    Message message = new Message();
                    message.what = Constant.HOMESCROLL;
                    EventBus.getDefault().post(message);
                } else {
                    ImmersionBar.with(this).transparentBar().init();
                    changeNavagationState(HOME_INDEX);
                }
                currentIndex = HOME_INDEX;
                break;
            case R.id.txt_remote:
                ImmersionBar.with(this).barColorInt(getResources().getColor(R.color.colorPrimary)).statusBarDarkFont(false).navigationBarEnable(false).init();
                changeNavagationState(REMOTE_INDEX);
                currentIndex = REMOTE_INDEX;
                break;
            case R.id.txt_mine:
                ImmersionBar.with(this).barColorInt(getResources().getColor(R.color.colorPrimary)).statusBarDarkFont(false).navigationBarEnable(false).init();
                changeNavagationState(CENTER_INDEX);
                currentIndex = CENTER_INDEX;
                break;
            default:
                break;
        }


    }

    private void changeNavagationState(int index) {
        FragmentManager fragmentManager = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction transaction = fragmentManager.beginTransaction();

        hideAllFragment(transaction);
        switch (index) {

            case HOME_INDEX:
                selected();
                txtHome.setSelected(true);
                if (f1 == null) {
                    f1 = HomeFragment.newInstance();
                    transaction.add(R.id.fragment_container, f1);
                } else {
                    transaction.show(f1);
                }
                break;
            case REMOTE_INDEX:
                selected();
                txtRemote.setSelected(true);
                if (f2 == null) {
                    f2 = RemoteFragment.newInstance(mActivity);
                    transaction.add(R.id.fragment_container, f2);
                } else {
                    transaction.show(f2);
                }
                break;
            case CENTER_INDEX:
                selected();
                txtMine.setSelected(true);
                if (f3 == null) {
                    f3 = MineFragment.newInstance();
                    transaction.add(R.id.fragment_container, f3);
                } else {
                    transaction.show(f3);
                }
                break;
            default:
                break;
        }

        transaction.commitAllowingStateLoss();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    @Override
    public void showDataSuccess(VersionEntity.PayLoadBean datas) {

    }

    @Override
    public void showVersion(VersionEntity.PayLoadBean caseCounts) {
        if (caseCounts != null && caseCounts.getAppUpdateLog() != null) {
            int vision = SystemUtil.getVersion(mContext);
            String newVision = caseCounts.getAppUpdateLog().getVersion();
            try {
                if (Integer.parseInt(newVision) > vision) {
                    showDialogVersion(MainActivity.this, caseCounts);
                }
            } catch (Exception e) {

            }
        }
    }

    //版本检测对话框
    public void showDialogVersion(final Context context, final VersionEntity.PayLoadBean beans) {

        final VersionEntity.PayLoadBean.AppUpdateLogBean updateLogs = beans.getAppUpdateLog();
        final VersionEntity.PayLoadBean.AppUpdateNoticeBean updateNotice = beans.getAppUpdateNotice();
        final String url = updateLogs.getDownloadUrl();
        mFileInfo = new DownLoadFileEntity("cmai_" + updateLogs.getVersionname() + ".apk", url);
        isForcedUpdate = updateLogs.getCompulsive();
        final Dialog dialog_window = new Dialog(context, R.style.ActionSheetDialogStyle);
        final List<String> updataContents = new ArrayList<>(16);
        View inflate = LayoutInflater.from(context).inflate(R.layout.set_check_version_dialog, null);
        ImageView cancel = (ImageView) inflate.findViewById(R.id.app_upload_back);
        TextView isOk = (TextView) inflate.findViewById(R.id.app_upload_btn);
        TextView isWait = (TextView) inflate.findViewById(R.id.app_waitupload_btn);
        TextView textView = (TextView) inflate.findViewById(R.id.app_upload_content);
        TextView versionCode = (TextView) inflate.findViewById(R.id.app_VersionCode);
        TextView promptContent = (TextView) inflate.findViewById(R.id.app_PromptContent);
        TextView forceContent = (TextView) inflate.findViewById(R.id.app_ForceContent);
        TextView updateProtocol = (TextView) inflate.findViewById(R.id.app_UpdateProtocol);
        RecyclerView rl_content = (RecyclerView) inflate.findViewById(R.id.app_Rl_UpadataContent);
        dialog_window.setContentView(inflate);
        if (updateNotice != null && !TextUtils.isEmpty(updateNotice.getNotice())) {
            forceContent.setVisibility(View.VISIBLE);
            forceContent.setText(updateNotice.getNotice());
            if (updateNotice.getNoticecolor() != null) {
                forceContent.setTextColor(Color.parseColor(updateNotice.getNoticecolor()));
            }
        } else {
            forceContent.setVisibility(View.GONE);
        }
        if (updateNotice != null && !TextUtils.isEmpty(updateNotice.getUrlname())) {
            updateProtocol.setVisibility(View.VISIBLE);
            updateProtocol.setText(updateNotice.getUrlname());
            updateProtocol.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(MainActivity.this, HealthArticalActivity.class);
                    intent.putExtra("Articleid", 101);
                    intent.putExtra("Author", updateNotice.getUrlname());
                    intent.putExtra("UserUpdateUrl", updateNotice.getUrl());
                    startActivity(intent);
                }
            });
        } else {
            updateProtocol.setVisibility(View.GONE);
        }
        switch (isForcedUpdate) {
            case 0:
                isWait.setVisibility(View.VISIBLE);
                break;
            case 1:
                dialog_window.setCanceledOnTouchOutside(false);
                dialog_window.setCancelable(false);
                isWait.setVisibility(View.GONE);
                break;
            default:
        }
        if (updateNotice.getAppsize() != 0) {
            float appLength = updateNotice.getAppsize() / 1024;
            BigDecimal b = new BigDecimal(appLength);
            float finalLength = b.setScale(2, BigDecimal.ROUND_HALF_UP).floatValue();
            promptContent.setText("建议您在Wi-Fi下更新，完成本次更新预计需要" + finalLength + "MB");
        }
        LinearLayoutManager layoutManager = new LinearLayoutManager(context);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rl_content.setLayoutManager(layoutManager);
        if (updateLogs.getVersionname() != null) {
            versionCode.setText(updateLogs.getVersionname());
        }
        if (updateLogs.getContent() != null && !TextUtils.isEmpty(updateLogs.getContent())) {
            String[] list = updateLogs.getContent().split("\r\n");
            for (int i = 0; i < list.length; i++) {
                updataContents.add(list[i]);
            }
        }
        CommonAdapter adapter = new CommonAdapter<String>(context, R.layout.dialog_update_version, updataContents) {
            @Override
            protected void convert(ViewHolder holder, final String s, int position) {
                final TextView content = holder.getView(R.id.dialog_UpdateCotent);
                content.setText(s);
            }
        };
        rl_content.setAdapter(adapter);
        Window window = dialog_window.getWindow();
        window.setGravity(Gravity.CENTER);
        WindowManager.LayoutParams layoutParams = window.getAttributes();
        layoutParams.y = 10;
        layoutParams.width = SystemUtil.getMetrics(context)[0];
        window.setAttributes(layoutParams);
        dialog_window.show();
        isWait.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog_window.dismiss();
            }
        });

        isOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DownLoadFileEntity info = mDownLoaderManger.checkData(url);
                final File file = new File(DownLoaderManger.FILE_PATH, "cmai_" + updateLogs.getVersionname() + ".apk");
                if (info != null && info.getUrl() != null) {
                    if (file.exists()) {
                        isShowDownLoadDialog(context, updateLogs, dialog_window);
                    } else {
                        mDownLoaderManger.deleteTask(mFileInfo, 0);
                        isShowDownLoadDialog(context, updateLogs, dialog_window);
                    }
                } else {
                    if (file.exists()) {
                        selfDialog = new SelfDialog(context);
                        selfDialog.setTitle("安装包已经下载，是否立即安装");
                        selfDialog.setYesOnclickListener("立即安装", new SelfDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                initStall(file);
                                selfDialog.dismiss();
                            }
                        });
                        selfDialog.setNoOnclickListener("以后再说",
                                new SelfDialog.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        selfDialog.dismiss();
                                    }
                                });
                        selfDialog.show();
                    } else {
                        isShowDownLoadDialog(context, updateLogs, dialog_window);
                    }
                }
            }
        });
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                switch (isForcedUpdate) {
                    case 0:
                        dialog_window.dismiss();
                        break;
                    case 1:
                        dialog_window.dismiss();
                        exits();
                        break;
                    default:
                }

            }
        });
    }

    //type 0:下载 1：断点下载
    private void isShowDownLoadDialog(final Context context, final VersionEntity.PayLoadBean.AppUpdateLogBean beans, Dialog dialog_window) {
        ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
        if (activeNetworkInfo != null) {
            if (SystemUtil.isMobileConnected(context)) {
                ThreadUtil.runInUIThread(context, new Runnable() {
                    @Override
                    public void run() {
                        selfDialog = new SelfDialog(context);
                        selfDialog.setTitle("当前正处于移动网络下，如立即更新" + "会消耗您28.3MB数据流量");
                        selfDialog.setYesOnclickListener("立即更新", new SelfDialog.onYesOnclickListener() {
                            @Override
                            public void onYesClick() {
                                selfDialog.dismiss();
                                showDownLoadDialog(beans, context);
                            }
                        });
                        selfDialog.setNoOnclickListener("暂不更新",
                                new SelfDialog.onNoOnclickListener() {
                                    @Override
                                    public void onNoClick() {
                                        selfDialog.dismiss();
                                        if (isForcedUpdate == 1) {
                                            exits();
                                        }
                                    }
                                });
                        selfDialog.show();
                    }
                });
            } else {
                showDownLoadDialog(beans, context);
            }
            dialog_window.dismiss();
        } else {
            ToastUtils.showAtCenter("当前无网络，请检查网络连接");
        }
    }

    //安装apk
    private void initStall(File file) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(Uri.fromFile(file), "application/vnd.android.package-archive");
        startActivity(intent);
    }

    //type 0:下载 1：断点下载
    public void showDownLoadDialog(final VersionEntity.PayLoadBean.AppUpdateLogBean beans, final Context context) {
        switch (beans.getCompulsive()) {
            case 1:
                mUpdateProgressDialog = new UpdateProgressDialog(context);
                mUpdateProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
                mUpdateProgressDialog.setIndeterminate(true);
                mUpdateProgressDialog.setCanceledOnTouchOutside(false);
                mUpdateProgressDialog.setCancelable(false);
                mUpdateProgressDialog.show();
                break;
        }
        isDown[0] = true;
        isStart = true;
    }

    //下载进度更新
    @Override
    public void updateProgress(int max, int progress, File file) {
        if (progress == max) {
            if (isForcedUpdate == 1) {
                mDownLoaderManger.deleteTask(mFileInfo, 1);
                initStall(file);
                exits();
            }
        } else {
            if (isForcedUpdate == 1) {
                mUpdateProgressDialog.setMax(max);
                mUpdateProgressDialog.setProgress(progress);
            }
        }
    }

    //退出应用
    public void exits() {
        finish();
        System.exit(0);
        Process.killProcess(Process.myPid());
    }

}
